package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.common.utils.FileTypeUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmFileMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmHazardMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EntityVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.Organization;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.Hazard;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.HazardVo;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutEntityService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutOrganizationService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.HazardService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liyi on 2016/11/29.
 * 危害因素
 */
public class HazardServiceImpl implements HazardService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TdmHazardMapper tdmHazardMapper;
    @Autowired
    private TdmFileMapper tdmFileMapper;
    @Autowired(required = false)
    private OutEntityService outEntityService;
    @Autowired(required = false)
    public OutOrganizationService outOrganizationService;

    /**
     * 查看危害因素
     *
     * @param employeeVo
     * @param hazardVo
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> list(EmployeeVo employeeVo, HazardVo hazardVo) throws Exception {
        Map<String, Object> map = new HashMap<>();
        hazardVo.setLimit(hazardVo.getLimit() == null ? 10 : hazardVo.getLimit());
        hazardVo.setOffset(hazardVo.getOffset() == null ? 0 : hazardVo.getOffset());
        //设置过滤条件
        hazardVo.setFilterEmployeeId(employeeVo.getEmployeeId());
        hazardVo.setFilterOrgId(employeeVo.getOrgId());
        //查询
        map.put("total", tdmHazardMapper.queryCount(hazardVo));
        System.out.println("插入前主键为：" + hazardVo.getHazardId());
        map.put("rows", JSON.toJSON(tdmHazardMapper.queryList(hazardVo)));
        return map;
    }

    /**
     * 新增危害因素
     *
     * @param employeeVo
     * @param hazard
     * @throws Exception
     */
    @Override
    public void saveHazard(EmployeeVo employeeVo, Hazard hazard) throws Exception {
        if (hazard != null) {
            //设置危害对象所属组织
            if (StringUtils.isNotBlank(hazard.getEntityId())) {
                try {
                    EntityVo entityVo = outEntityService.getEntityByEntityId(hazard.getEntityId());
                    //问题对象ID是生产实体
                    if (entityVo != null) {
                        hazard.setOrgId(entityVo.getParentOrgId());
                        //问题对象ID不是生产实体，而是组织ID
                    } else {
                        hazard.setOrgId(hazard.getEntityId());
                    }
                    //问题对象ID不是生产实体，而是组织ID
                    Organization organization = outOrganizationService.queryOrganization(hazard.getEntityId());
                    if (organization != null) {
                        hazard.setOrgId(hazard.getEntityId());
                    }
                    if (entityVo == null && organization == null) {
                        hazard.setOrgId(employeeVo.getOrgId());
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            } else {
                hazard.setOrgId(employeeVo.getOrgId());
            }
            // 设置ID
            hazard.setHazardId(UniqueUtil.uuid());
            // 设置创建人ID
            hazard.setCreateUserId(employeeVo.getEmployeeId());
            // 设置创建人时间
            hazard.setCreateTime(new Date());
            // 设置修改人ID
            hazard.setModifyUserId(employeeVo.getEmployeeId());
            // 设置修改人时间
            hazard.setModifyTime(new Date());
            // 设置删除状态
            hazard.setIsDelete((short) 0);
            // 保存危害因素信息
            tdmHazardMapper.insertSelective(hazard);
        }
    }

    /**
     * 修改危害因素
     *
     * @param employeeVo
     * @param hazard
     * @return
     */
    @Override
    public int updateByPrimaryKey(EmployeeVo employeeVo, Hazard hazard) {
        // 设置修改人ID
        hazard.setModifyUserId(employeeVo.getEmployeeId());
        // 设置修改人时间
        hazard.setModifyTime(new Date());
        // 修改危害因素
        return tdmHazardMapper.updateByPrimaryKeySelective(hazard);
    }

    /**
     * 删除危害因素:软删除
     *
     * @param list
     * @return
     */
    @Override
    public int delByIds(List<String> list) throws Exception {
        if (list == null || (list != null && list.size() == 0)) {
            return 0;
        }
        // 批量修改
        int i = tdmHazardMapper.updateStateByIds(list);

        return i;
    }

    /**
     * 根据ID查询危害因素
     *
     * @param hazardId
     * @return
     */
    @Override
    public Hazard findHazardById(String hazardId) throws Exception {
        return tdmHazardMapper.selectByPrimaryKey(hazardId);
    }

    /**
     * 查询
     *
     * @param hazardId
     * @return
     * @throws Exception
     */
    @Override
    public HazardVo findHazardByIdNew(String hazardId) throws Exception {
        if (StringUtils.isBlank(hazardId)) {
            return null;
        }

        HazardVo hazardVo = tdmHazardMapper.selectByPrimaryKeyNew(hazardId);

        return hazardVo;
    }

    /**
     * 保存危害因素
     * 注意：解开启事务，不能抛异常
     *
     * @param employeeVo
     * @param hazard
     * @param uploadFiles
     * @param deletedFiles
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int save(EmployeeVo employeeVo, Hazard hazard, String uploadFiles, String deletedFiles) {
        if (hazard == null) {
            return 0;
        }

        //设置危害对象所属组织
        setOrgIdByCondition(employeeVo, hazard);
        // 设置ID
        hazard.setHazardId(UniqueUtil.uuid());
        // 设置创建人ID
        hazard.setCreateUserId(employeeVo.getEmployeeId());
        // 设置创建人时间
        hazard.setCreateTime(new Date());
        // 设置修改人ID
        hazard.setModifyUserId(employeeVo.getEmployeeId());
        // 设置修改人时间
        hazard.setModifyTime(new Date());
        // 设置删除状态
        hazard.setIsDelete((short) 0);
        // 保存危害因素
        int a = tdmHazardMapper.insertSelective(hazard);
        if (StringUtils.isNotBlank(uploadFiles)) {
            // 强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);
            // 重新设置附件属性
            for (int i = 0; i < listFiles.size(); i++) {
                File _file = listFiles.get(i);
                // 设置主键
                _file.setFileId(UniqueUtil.uuid());
                // 设置业务数据id
                _file.setBusinessId(hazard.getHazardId());
                _file.setFileType((short) FileTypeUtil.getFileTypeByFileName(_file.getFileName()));
            }
            // 必须判断非空
            if (listFiles != null && listFiles.size() > 0) {
                a += tdmFileMapper.insertByList(listFiles);
            }
        }
        return a;
    }

    /**
     * 更新危害因素
     *
     * @param employeeVo
     * @param hazard
     * @param deletedFiles
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int update(EmployeeVo employeeVo, Hazard hazard, String uploadFiles, String deletedFiles) {
        if (hazard == null) {
            return 0;
        }

        //设置危害对象所属组织
        setOrgIdByCondition(employeeVo, hazard);
        // 设置修改人ID
        hazard.setModifyUserId(employeeVo.getEmployeeId());
        // 设置修改人时间
        hazard.setModifyTime(new Date());
        // 修改危害因素
        int a = tdmHazardMapper.updateByPrimaryKeySelective(hazard);


        // 更新附件信息
        if (StringUtils.isNotBlank(uploadFiles)) {
            // 强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                // 重新设置附件属性
                String pId = hazard.getHazardId();
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    // 设置主键
                    _file.setFileId(UniqueUtil.uuid());
                    // 设置业务数据id
                    _file.setBusinessId(pId);
                    _file.setFileType((short) FileTypeUtil.getFileTypeByFileName(_file.getFileName()));
                }
                a += tdmFileMapper.insertByList(listFiles);
            }
        }
        // 需要删除的附件信息
        if (deletedFiles != null && !deletedFiles.equals("")) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(deletedFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    tdmFileMapper.deleteByPrimaryKey(_file.getFileId());
                }
            }
        }
        return a;
    }


    /**
     * 设置危害对象所属组织
     *
     * @param employeeVo
     * @param hazard
     */
    public void setOrgIdByCondition(EmployeeVo employeeVo, Hazard hazard) {
        //设置危害对象所属组织
        if (StringUtils.isNotBlank(hazard.getEntityId())) {
            try {
                EntityVo entityVo = outEntityService.getEntityByEntityId(hazard.getEntityId());
                //危害对象ID是生产实体
                if (entityVo != null) {
                    hazard.setOrgId(entityVo.getParentOrgId());
                    //危害对象ID不是生产实体，而是组织ID
                }
                //危害对象ID不是生产实体，而是组织ID
                Organization organization = outOrganizationService.queryOrganization(hazard.getEntityId());
                if (organization != null) {
                    hazard.setOrgId(hazard.getEntityId());
                }
                if (entityVo == null && organization == null) {
                    hazard.setOrgId(employeeVo.getOrgId());
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        } else {
            hazard.setOrgId(employeeVo.getOrgId());
        }
    }
}
